<template>
  <div>
    <el-button style="margin-bottom: 10px" type="primary" class="fl" size="mini" @click="createItem">
      添加规则明细</el-button>
    <el-button v-if="sortFlag" :loading="sortLoading" style="margin-bottom: 10px" type="success" class="fl" size="mini"
      @click="saveSort">
      保存排序</el-button>
    <el-tag class="ml-10" v-else type="info">提示：拖动表格行可进行排序</el-tag>
    <z-table ref="dragTable" v-loading="tableLoading" :list="list" :tableProps="tableProps" :columns="columns">
      <template #operation="{row,$index}">
        <a href="#" class="text-blue" v-permission="'barcodeInfo.edit'"
          @click.prevent.stop="editItem(row,$index)">编辑</a>
        <a style="margin-left:5px;" href="#" class="text-red" v-permission=" 'barcodeInfo.delete'"
          @click.prevent.stop="deleteItem(row,$index)">删除</a>
      </template>
    </z-table>

    <z-form-dialog :name="name" :data="data" :formProps="formProps" :fields="fields" :visible.sync="editFormVisible">

      <template #footer>
        <el-button @click="editFormVisible = false">取消</el-button>
        <el-button v-if="!formProps.disabled" type="primary" @click.native="submit(false)" :loading="submitLoading">确认
        </el-button>
        <el-button v-if="!formProps.disabled && !isCommon" type="warning" @click.native="submit(true)"
          :loading="submitLoading2">确认并下一步
        </el-button>
      </template>
    </z-form-dialog>
  </div>
</template>

<script>
import commonMixin from '@/views/_common/mixin'
import { getToken } from '@/utils/auth'
import Sortable from 'sortablejs'
export default {
  mixins: [commonMixin],
  props: {
    barCodeId: {
      type: String,
      default: '',
    },
    isCommon: {
      type: Number,
      default: 0,
    },
  },
  watch: {
    barCodeId: {
      handler() {
        this.getList()
      },
    },
  },
  data() {
    return {
      api: this.$api.barcodeRule,
      apiSingle: this.$api.barcodeRule + 'getbyid',
      baseUrl: this.$api.baseUrl,
      apiCreate: this.$api.barcodeRule + 'modify',
      apiEdit: this.$api.barcodeRule + 'detailmodify',
      apiDelete: this.$api.barcodeRule + 'detaildelete',
      apiList: this.$api.barcodeRule + 'detailgetlist',
      name: '条码规则明细',
      sortFlag: false,
      sortLoading: false,
      detailPageLoading: false,
      columns: [
        { title: '区段序号', key: 'sequence', width: 72 },
        { title: '区段类型', key: 'coding_type', width: 100 },
        { title: '要素代码', key: 'coding_param', width: 100 },
        { title: '要素名称', key: 'coding_desc' },
        { title: '值', key: 'field_value', width: 100 },
        { title: '修改人', key: 'modify_user', width: 100 },
        { title: '最后修改', key: 'modify_time', width: 140 },
      ],
      fields: [
        {
          title: '区段序号',
          key: 'sequence',
          name: 'text',
          props: { disbaled: true },
          tips: '序号越小区段越靠前',
        },
        {
          title: '区段类型',
          key: 'factor_type',
          required: true,
          name: 'select',
          options: [],
          props: {},
          events: { change: null },
        },
        {
          title: '要素',
          key: 'factor_id',
          required: true,
          name: 'select',
          options: [],
          props: {},
          events: { change: null },
        },
        {
          title: '要素值',
          props: { disbaled: false },
          key: 'field_value',
          name: 'text',
          options: [],
          tips: '区段类型为View时，选择字段名，区段值类型为Param时，填写参数名',
        },
        {
          title: '流水号重置',
          key: 'reset_flag',
          span: 12,
          required: true,
          name: 'switch',
          tips: '选中表示此区段值的变化，将引起流水号的重置',
          props: { disabled: false, activeValue: 'Y', inactiveValue: 'N', reset_flag: 'N' },
        },
        {
          title: '流水号起始值',
          key: 'reset_start_value',
          span: 12,
          name: 'number',
          props: { min: 0, disbaled: false },
          tips: '填写10进制整数值',
        },
        { title: '备注', key: 'remarks', name: 'textarea' },
      ],
      tableProps: {
        border: true,
        // opsColWith: 80,
        // fixed: false,
        'row-key': 'id',
        highlightCurrentRow: false,
        hideOperations: false,
      },
      formProps: {
        dialogWidth: '70%',
        labelWidth: '140px',
      },
      submitLoading2: false,
      data: {},
      sortList: [],
      factorOptions: [],
      codingTypes: [
        { label: 'Datetime 日期时间', value: 'Datetime' },
        { label: 'String 固定字串', value: 'String' },
        { label: 'SerialNumber 流水号', value: 'SerialNumber' },
        { label: 'View 视图', value: 'View' },
        { label: 'Param 参数', value: 'Param' },
      ],
    }
  },

  methods: {
    initSortable() {
      // 获取表格row的父节点
      const ele = this.$refs.dragTable.$el.querySelector('.el-table__body > tbody')
      // 创建拖拽实例
      let dragTable = Sortable.create(ele, {
        animation: 150, //动画
        disabled: false, // 拖拽不可用? false 启用（刚刚渲染表格的时候起作用，后面不起作用）
        // 开始拖动事件
        onStart: () => {},
        // 结束拖动事件
        onEnd: ({ newIndex, oldIndex }) => {
          this.sortFlag = true
          let tmp = this.sortList[newIndex]
          this.sortList[newIndex] = this.sortList[oldIndex]
          this.sortList[oldIndex] = tmp
        },
      })
    },
    getList() {
      this.pageLoading = true
      this.$request(this.$api.barcodeRule + 'detailgetlist', {
        rule_id: this.barCodeId,
        size: 999,
        page: 1,
      })
        .then((r) => {
          this.pageLoading = false
          this.list = r.list
          this.sortList = r.list.map((v) => {
            return v.id
          })
          this.initSortable()
        })
        .catch((e) => {
          this.pageLoading = false
        })
    },
    createItem() {
      let q = this.list.length || 0
      this.data = { barcode_rule_id: this.barCodeId, sequence: q + 1 }
      this.editFormVisible = true
    },
    saveSort() {
      if (this.sortList.length == 0) return this.$message.error('没有需要保存的数据')
      this.sortLoading = true
      this.$request(this.$api.barcodeRule + 'detailSaveSort', this.sortList, 'post').then((r) => {
        this.sortLoading = false
        this.$message.success('保存排序成功。')
        this.getList()
      })
    },
    editItem(row) {
      this.pageLoading = true
      this.$request(this.$api.barcodeRule + 'detailgetbyid', {
        id: row.id,
      })
        .then((r) => {
          this.pageLoading = false
          let data = r
          data.factor_type = row.coding_type
          this.data = data
          this.typeChange(data.factor_type)
          this.factorChange(data.factor_id)
          this.editFormVisible = true
        })
        .catch(() => {
          this.pageLoading = false
        })
    },
    typeChange(v) {
      this.fields.find((i) => i.key == 'field_value').props.disabled = true
      this.fields.find((i) => i.key == 'reset_start_value').props.disabled = true
      this.fields.find((i) => i.key == 'reset_flag').props.disabled = true
      if (v == 'SerialNumber') this.fields.find((i) => i.key == 'reset_start_value').props.disabled = false
      if (v == 'View' || v == 'Param') this.fields.find((i) => i.key == 'field_value').props.disabled = false
      if (v != 'SerialNumber') this.fields.find((i) => i.key == 'reset_flag').props.disabled = false
      var tmp = this.fields.find((i) => i.key == 'factor_id')
      tmp.options = this.factorOptions.filter((i) => i.type == v)
    },
    factorChange(v) {
      var f = this.factorOptions.find((i) => i.value == v)
      if (this.data.factor_type == 'View') {
        this.$request(this.$api.param + 'getbyname', { type: 'LABEL_VIEW_FIELDS', name: f.coding_param }).then((r) => {
          var tmp = this.fields.find((i) => i.key == 'field_value')
          tmp.name = 'select'
          tmp.options = r.map((i) => ({
            label: `${i.param_value} ${i.param_condition1}`,
            value: i.param_value,
          }))
        })
      } else {
        var tmp = this.fields.find((i) => i.key == 'field_value')
        tmp.name = 'text'
        tmp.options = []
      }
    },
    submit(flag) {
      let tmp = _.cloneDeep(this.data)
      if (!flag) this.submitLoading = true
      else this.submitLoading2 = true

      let url = this.apiEdit
      let check = this.validataData(this.fields, tmp)
      if (!check) {
        if (!flag) this.submitLoading = false
        else this.submitLoading2 = false
        return
      }
      this.$request(url, tmp, 'post')
        .then((r) => {
          if (!flag) this.submitLoading = false
          else this.submitLoading2 = false
          this.$message({
            message: '操作成功',
            type: 'success',
          })
          this.getList()
          if (flag) {
            this.$emit('update:currentTab', 'tab3')
          }
          this.editFormVisible = false
        })
        .catch(() => {
          if (!flag) this.submitLoading = false
          else this.submitLoading2 = false
        })
    },
    submit2(flag) {
      this.$emit('update:currentTab', 'tab3')
    },
  },
  activated() {
    this.$request(this.$api.factor + 'getlist', { page: 1, size: 99 }).then((r) => {
      this.factorOptions = r.list.map((i) => {
        return {
          label: `${i.coding_param} ${i.coding_desc}  ${i.sample_value ? '示例：' + i.sample_value : ''}`,
          value: i.id,
          type: i.coding_type,
          coding_param: i.coding_param,
        }
      })
    })
  },
  created() {
    this.fields.find((i) => i.key == 'sequence').props.disabled = true
    this.getList()
    var tmp = this.fields.find((i) => i.key == 'factor_type')
    tmp.options = this.codingTypes
    tmp.events.change = this.typeChange
    tmp = this.fields.find((i) => i.key == 'factor_id')
    tmp.events.change = this.factorChange
    this.$request(this.$api.factor + 'getlist', { page: 1, size: 99 }).then((r) => {
      this.factorOptions = r.list.map((i) => {
        return {
          label: `${i.coding_param} ${i.coding_desc}  ${i.sample_value ? '示例：' + i.sample_value : ''}`,
          value: i.id,
          type: i.coding_type,
          coding_param: i.coding_param,
        }
      })
    })
  },
}
</script>

<style lang="scss">
</style>